#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#
#替换自动打包的配置信息
#参考天天消宝石出包流程写的
#

import os
import shutil
import GameInfoReader
import ChannelConfigReader
import string
import ManifestParser
import AutoGenApk
import SwitchChannel
import GameCustomOper
import time

class UpPackConfig(object):
	def __init__(self,projectconfigfile,channelconfigfile):
		self.__projectconfigfile = projectconfigfile
		self.__channelconfigfile = channelconfigfile

		self.__projectInfoRd = GameInfoReader.GameInfoReader(self.__projectconfigfile)
		self.__channelInfoRd = ChannelConfigReader.ChannelConfigReader(self.__channelconfigfile)

		#读取联通woshopid对应的jar目录,例如：key为00018253，对应的文件夹名就是1439192542730_00018253_20150821
		wozipfilepath = self.__projectInfoRd.getOneProjectInfo("wozipfilepath")
		if( len(wozipfilepath) > 0 ):
			self.__woShopJarDict = {}
			files = os.listdir(self.__projectInfoRd.getOneProjectInfo("wozipfilepath"))
			for f in files:
				fullpath = self.__projectInfoRd.getOneProjectInfo("wozipfilepath") + "/" + f
				if(os.path.isdir(fullpath)):
					key = f.split('_')[1]
					self.__woShopJarDict[key]=fullpath

	def getChannelDict(self):
		return self.__channelInfoRd.getConfigDict()

	def getAppCopyPath(self):
		return self.__projectInfoRd.getOneProjectInfo("app_copy_path")

	def getAppOriginalPath(self):
		return self.__projectInfoRd.getOneProjectInfo("app_original_path")

	def isChildChannel(self, channelname):
		channelsdict = self.__channelInfoRd.getConfigDict()
		channelinfo = channelsdict[channelname].getChannelInfo()
		if "root_channel" in channelinfo.keys():
			return True
		return False

	def updateConfigInfo(self):
		wozipfilepath = self.__projectInfoRd.getOneProjectInfo("wozipfilepath")
		app_original_path = self.__projectInfoRd.getOneProjectInfo("app_original_path")
		app_copy_path = self.__projectInfoRd.getOneProjectInfo("app_copy_path")
		sgand_project_path = self.__projectInfoRd.getOneProjectInfo("sgand_project_path")
		four_project_path = self.__projectInfoRd.getOneProjectInfo("four_project_path")
		gamepackagename = self.__projectInfoRd.getOneProjectInfo("packageName")
		weixin_project_path = self.__projectInfoRd.getOneProjectInfo("weixin_project_path")

		srcManifestFile = app_original_path + "/AndroidManifest.xml"
		desManifestFile = app_copy_path + "/AndroidManifest.xml"
		
		#执行游戏定制操作
		GameCustomOper.gameCustomOperBegin()
		
		#更新AndroidManifest.xml和WoShop的jar包
		channelsdict = self.__channelInfoRd.getConfigDict()
		for channelname in channelsdict:
			channelinfo = channelsdict[channelname].getChannelInfo()
			
			#
			ref_project_path = channelinfo["refprojectpath"]
			channeloperfilename = channelinfo["channeloperfilepath"]
			woshopid = self.__channelInfoRd.getConfigDict()[channelname].getChannelInfo()["woshopid"]
			
			#copy游戏工程
			if(True == os.path.exists(app_copy_path)):
				shutil.rmtree(app_copy_path,True)
			SwitchChannel.dirBackup(app_original_path,app_copy_path)

			#copy assets目录
			if( len(ref_project_path) > 0 ):
				SwitchChannel.dirBackup(ref_project_path+"/assets",app_copy_path+"/assets")

			#修正游戏工程的依赖库信息(因为操作的是copy工程)
			SwitchChannel.correctRefRelLib(app_original_path,app_copy_path,"project.properties")

			#执行每个渠道的定制操作
			if( len(channeloperfilename) > 0 ):
				SwitchChannel.carryChannelOper(channeloperfilename)

			#给SGAnd/project.properties文件加上依赖的渠道库信息(里面有完成修正操作)
			if( len(sgand_project_path) > 0 
			and len(ref_project_path) > 0 ):
				SwitchChannel.addRefLibWithBackup(sgand_project_path,sgand_project_path,ref_project_path)

			#给FOUR工程替换联通配置.jar文件
			if( len(wozipfilepath) > 0 
			and len(four_project_path) > 0
			and len(woshopid) > 0 ):
				woshopjardir = self.__woShopJarDict[woshopid]
				if(woshopjardir == None):
					raise Exception("woShop jardir with key : ",woshopid,"is not exist!")
				basefilepath = woshopjardir + "/Multimode_UniPay_base.jar"
				payinfofilepath = woshopjardir + "/Multimode_UniPay_payinfo.jar"
				if(False == os.path.exists(basefilepath)):
					raise Exception("basefilepath ",basefilepath," is not exist!")
				if(False == os.path.exists(payinfofilepath)):
					raise Exception("payinfofilepath ",payinfofilepath," is not exist!")
				shutil.copyfile(basefilepath,four_project_path + "/libs/Multimode_UniPay_base.jar")
				shutil.copyfile(payinfofilepath,four_project_path + "/libs/Multimode_UniPay_payinfo.jar")

			#修改微信工程的目录
			if( len(weixin_project_path) > 0 
			and len(channelinfo["packagename"]) > 0 
			and len(gamepackagename) ):
				print("SwitchChannel.changeWXEntryPackage")
				SwitchChannel.changeWXEntryPackage(weixin_project_path,gamepackagename,channelinfo["packagename"])

			#更新AndroidManifest.xml：包括：
			# package、android:versionCode、android:versionName
			# 电信配置(egame_channel)、插件配置(l_appid、l_channel)、友盟渠道(umengchannel)
			# wxappid，wxappsecret,WXEntryActivity的前缀
			# SOULGAME_APPKEY、SOULGAME_CHANNEL
			ManifestParser.run(desManifestFile,desManifestFile,channelinfo,self.__projectInfoRd)

			#生成apk
			AutoGenApk.getReady()
			AutoGenApk.antCreateApk()
			AutoGenApk.copyApkToOutput(channelname)

			#恢复微信工程的修改(暂时取消)
			if( len(weixin_project_path) > 0 
			and len(channelinfo["packagename"]) > 0 
			and len(gamepackagename) ):
				print("SwitchChannel.restpreWXEntryPackage")
				#SwitchChannel.restpreWXEntryPackage(weixin_project_path,channelinfo["packagename"])

			#恢复对SGAnd/project.properties文件(暂时取消)
			if( len(sgand_project_path) > 0 
			and len(ref_project_path) > 0 ):
				print("")
				#SwitchChannel.restoreProjectProperties(sgand_project_path)

			#执行渠道的恢复操作
			if( len(channeloperfilename) > 0 ):
				SwitchChannel.restoreChannelOper()

			#sleep
			print("sleep 5 seconds......")
			time.sleep(5)
		
		#执行渠道定制操作的恢复操作
		GameCustomOper.gameCustomOperEnd()
		
	def updateConfigInfoWithChannel(self, channelname):
		wozipfilepath = self.__projectInfoRd.getOneProjectInfo("wozipfilepath")
		app_original_path = self.__projectInfoRd.getOneProjectInfo("app_original_path")
		app_copy_path = self.__projectInfoRd.getOneProjectInfo("app_copy_path")
		sgand_project_path = self.__projectInfoRd.getOneProjectInfo("sgand_project_path")
		four_project_path = self.__projectInfoRd.getOneProjectInfo("four_project_path")
		gamepackagename = self.__projectInfoRd.getOneProjectInfo("packageName")
		weixin_project_path = self.__projectInfoRd.getOneProjectInfo("weixin_project_path")

		srcManifestFile = app_original_path + "/AndroidManifest.xml"
		desManifestFile = app_copy_path + "/AndroidManifest.xml"
		
		#执行游戏定制操作
		GameCustomOper.gameCustomOperBegin()
		
		#更新AndroidManifest.xml和WoShop的jar包
		channelsdict = self.__channelInfoRd.getConfigDict()

		channelinfo = channelsdict[channelname].getChannelInfo()
		
		#
		ref_project_path = channelinfo["refprojectpath"]
		channeloperfilename = channelinfo["channeloperfilepath"]
		woshopid = self.__channelInfoRd.getConfigDict()[channelname].getChannelInfo()["woshopid"]
		
		#copy游戏工程
		if(True == os.path.exists(app_copy_path)):
			shutil.rmtree(app_copy_path,True)
		SwitchChannel.dirBackup(app_original_path,app_copy_path)

		#copy assets目录
		if( len(ref_project_path) > 0 ):
			SwitchChannel.dirBackup(ref_project_path+"/assets",app_copy_path+"/assets")

		#修正游戏工程的依赖库信息(因为操作的是copy工程)
		SwitchChannel.correctRefRelLib(app_original_path,app_copy_path,"project.properties")

		#执行每个渠道的定制操作
		if( len(channeloperfilename) > 0 ):
			SwitchChannel.carryChannelOper(channeloperfilename)

		#给SGAnd/project.properties文件加上依赖的渠道库信息(里面有完成修正操作)
		if( len(sgand_project_path) > 0 
		and len(ref_project_path) > 0 ):
			SwitchChannel.addRefLibWithBackup(sgand_project_path,sgand_project_path,ref_project_path)

		#给FOUR工程替换联通配置.jar文件
		if( len(wozipfilepath) > 0 
		and len(four_project_path) > 0
		and len(woshopid) > 0 ):
			woshopjardir = self.__woShopJarDict[woshopid]
			if(woshopjardir == None):
				raise Exception("woShop jardir with key : ",woshopid,"is not exist!")
			basefilepath = woshopjardir + "/Multimode_UniPay_base.jar"
			payinfofilepath = woshopjardir + "/Multimode_UniPay_payinfo.jar"
			if(False == os.path.exists(basefilepath)):
				raise Exception("basefilepath ",basefilepath," is not exist!")
			if(False == os.path.exists(payinfofilepath)):
				raise Exception("payinfofilepath ",payinfofilepath," is not exist!")
			shutil.copyfile(basefilepath,four_project_path + "/libs/Multimode_UniPay_base.jar")
			shutil.copyfile(payinfofilepath,four_project_path + "/libs/Multimode_UniPay_payinfo.jar")

		#修改微信工程的目录
		if( len(weixin_project_path) > 0 
		and len(channelinfo["packagename"]) > 0 
		and len(gamepackagename) ):
			print("SwitchChannel.changeWXEntryPackage")
			SwitchChannel.changeWXEntryPackage(weixin_project_path,gamepackagename,channelinfo["packagename"])

		#更新AndroidManifest.xml：包括：
		# package、android:versionCode、android:versionName
		# 电信配置(egame_channel)、插件配置(l_appid、l_channel)、友盟渠道(umengchannel)
		# wxappid，wxappsecret,WXEntryActivity的前缀
		# SOULGAME_APPKEY、SOULGAME_CHANNEL
		ManifestParser.run(desManifestFile,desManifestFile,channelinfo,self.__projectInfoRd)

		#生成apk
		AutoGenApk.getReady()
		AutoGenApk.antCreateApk()
		AutoGenApk.copyApkToOutput(channelname)

		#恢复微信工程的修改(暂时取消)
		if( len(weixin_project_path) > 0 
		and len(channelinfo["packagename"]) > 0 
		and len(gamepackagename) ):
			print("SwitchChannel.restpreWXEntryPackage")
			#SwitchChannel.restpreWXEntryPackage(weixin_project_path,channelinfo["packagename"])

		#恢复对SGAnd/project.properties文件(暂时取消)
		if( len(sgand_project_path) > 0 
		and len(ref_project_path) > 0 ):
			print("")
			#SwitchChannel.restoreProjectProperties(sgand_project_path)

		#执行渠道的恢复操作
		if( len(channeloperfilename) > 0 ):
			SwitchChannel.restoreChannelOper()

		#sleep
		print("sleep 5 seconds......")
		time.sleep(5)
		
		#执行渠道定制操作的恢复操作
		GameCustomOper.gameCustomOperEnd()


if __name__=="__main__":
	updateConfigObj = UpPackConfig("./userconfig/gameinfo.conf","./userconfig/channelinfolist.conf")
	#更新信息并自动打包
	updateConfigObj.updateConfigInfo()

